<script setup lang="ts">
import RoomStatus from './components/RoomStatus.vue'
import RoomMessage from './components/RoomMessage.vue'
import RoomAction from './components/RoomAction.vue'
import { Socket, io } from 'socket.io-client'
import { baseURL } from '@/utils/request'
import { onMounted } from 'vue'
import { useUserStore } from '@/stores'
import { useRoute } from 'vue-router'
import { onUnmounted, ref } from 'vue'
import type { Message, TimeMessages } from '@/types/room'
import { MsgType, OrderType } from '@/enums'
import type { ConsultOrderItem, Image } from '@/types/consult'
import { getConsultOrderDetail } from '@/services/consult'
import { showToast } from 'vant'

const store = useUserStore()
const route = useRoute()
let socket: Socket
const list = ref<Message[]>([])
const consult = ref<ConsultOrderItem>()

const loadConsult = async () => {
  const res = await getConsultOrderDetail(route.query.orderId as string)
  consult.value = res.data
}
const one = ref(true)
onMounted(async () => {
  loadConsult()
  socket = io(baseURL, {
    auth: {
      token: `Bearer ${store.user?.token}`
    },
    query: {
      orderId: route.query.orderId
    }
  })
  socket.on('chatMsgList', ({ data }: { data: TimeMessages[] }) => {
    // 准备转换常规消息列表
    const arr: Message[] = []
    data.forEach((item, i) => {
      arr.push({
        msgType: MsgType.Notify,
        msg: { content: item.createTime },
        createTime: item.createTime,
        id: item.createTime
      })
      arr.push(...item.items)
    })
    if (!arr.length) showToast('没有更多了...')
    list.value.unshift(...arr)
    if (one.value) {
      setTimeout(() => {
        window.scrollTo(0, document.body.scrollHeight)
      }, 200)
      one.value = false
    }
  })
  socket.on('connect', () => {
    // 建立连接成功
    console.log('connect')
  })
  socket.on('error', (err) => {
    // 异常错误消息
    console.log('error', err)
  })
  socket.on('disconnect', () => {
    // 已经断开连接
    console.log('disconnect')
  })
  // 监听订单状态变化
  socket.on('statusChange', () => loadConsult())
  // 接收消息
  socket.on('receiveChatMsg', (event) => {
    list.value.push(event)
    setTimeout(() => {
      window.scrollTo(0, document.body.scrollHeight)
    }, 100)
  })
})
onUnmounted(() => {
  socket.close()
})
const ontext = (text: string) => {
  // console.log(text)

  // 聊天-发送对话信息
  // 发送信息需要  发送人  收消息人  消息类型  消息内容
  socket.emit('sendChatMsg', {
    from: store.user?.id,
    to: consult.value?.docInfo?.id,
    msgType: MsgType.MsgText,
    msg: { content: text }
  })
}
const onsendImage = (image: Image) => {
  console.log(image)
  socket.emit('sendChatMsg', {
    from: store.user?.id,
    to: consult.value?.docInfo?.id,
    msgType: MsgType.MsgImage,
    msg: { picture: image }
  })
}

const loading = ref(false)
const onRefresh = () => {
  socket.emit(
    'getChatMsgList',
    5,
    list.value[0].createTime,
    route.query.orderId
  )
  loading.value = false
}
</script>

<template>
  <div class="room-page">
    <cp-nav-bar title="医生问诊室" />
    <room-status :status="consult?.status" :countdown="consult?.countdown" />
    <van-pull-refresh v-model="loading" @refresh="onRefresh">
      <room-message :list="list" />
    </van-pull-refresh>
    <room-action
      :disabled="consult?.status !== OrderType.ConsultChat"
      @send-text="ontext"
      @send-image="onsendImage"
    />
  </div>
</template>

<style lang="scss" scoped>
.room-page {
  padding-top: 90px;
  padding-bottom: 60px;
  min-height: 100vh;
  box-sizing: border-box;
  background-color: var(--cp-bg);
  .van-pull-refresh {
    width: 100%;
    min-height: calc(100vh - 150px);
  }
}
</style>
